package com.kw.sqlsession;

import com.kw.pojo.Configuration;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Medivh on 2020/5/8.
 * 愿我出走半生,归来仍是少年
 */
public class DefaultSqlSession implements SqlSession {

    Configuration configuration;


    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
        return new SimpleExecutor().query(configuration,configuration.getMappedStatementMap().get(statementId),params);
    }
//
    @Override
    public <T> T selectOne(String statementId, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, IntrospectionException, InstantiationException {
        return (T) selectList(statementId,params).get(0);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用jdk动态代理 来为dao接口生成代理对象并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层执行jdbc 根据不同情况执行不同sql
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();


                String statementId = className+"."+methodName;

                //准备参数2 params
                //获取返回值类型
                Type genericReturnType = method.getGenericReturnType();
                if(genericReturnType instanceof ParameterizedType){
                    List<Object> objects = selectList(statementId,args);
                    return  objects;
                }


                //1statementId, sql唯一标示
                return selectList(statementId,args);
            }
        });

        return (T) proxyInstance;
    }
}
